package com.remarryapp.modules;

import android.app.Activity;
import android.content.Intent;

import com.facebook.react.bridge.ActivityEventListener;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.BaseActivityEventListener;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableArray;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.remarryapp.pictureselector.GlideEngine;

import java.util.List;

import static android.app.Activity.RESULT_OK;

public class ImagePreviewModule extends ReactContextBaseJavaModule {
    private Promise mPromise;

    private final ActivityEventListener mActivityEventListener = new BaseActivityEventListener() {

        @Override
        public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
            if (resultCode == RESULT_OK) {
                switch (requestCode) {
                    case PictureConfig.CHOOSE_REQUEST:
                        WritableArray array = Arguments.createArray();
                        // 结果回调
                        List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                        for (int i = 0; i < selectList.size(); i++) {
                            String path = selectList.get(i).getPath();
                            array.pushString(path);
                        }
                        mPromise.resolve(array);
                        break;
                    default:
                        break;
                }
            }
        }
    };

    public ImagePreviewModule(ReactApplicationContext reactContext) {
        super(reactContext);
        // Add the listener for `onActivityResult`
        reactContext.addActivityEventListener(mActivityEventListener);
    }

    @Override
    public String getName() {
        return "ImagePreviewModule";
    }

    @ReactMethod
    public void downloadImage(String imageUrl) {
//        Log.i("hsf","=========downloadImage======");
        PictureSelector.create(getCurrentActivity()).openGallery(PictureMimeType.ofImage()).loadImageEngine(GlideEngine.createGlideEngine()).forResult(PictureConfig.CHOOSE_REQUEST);
    }

    @ReactMethod
    public void select(int maxCount, Promise promise) {
//        Log.i("hsf","=========downloadImage======");
        mPromise = promise;
        PictureSelector.create(getCurrentActivity()).openGallery(PictureMimeType.ofImage()).loadImageEngine(GlideEngine.createGlideEngine()).forResult(PictureConfig.CHOOSE_REQUEST);
    }
}
